function output = load_var(varargin)

%LOAD_VAR Load user defined variables from MAT-file into workspace.
%   [output = ]LOAD_VAR() loads variables into workspace from the user logged in.
%        Variables are stored in a structure called 'vars'. Fields of 'vars' can be
%        added, modified, etc. in the following forms:
%   
%   LOAD_VAR('user', 'username') load variable structure of 'username' into
%       workspace.
%
%   LOAD_VAR('add', 'field', VALUE)
%   LOAD_VAR('add', 'field', VALUE, 'user', 'username') Add variable into
%       user defined structure. 'username' defines user other than currently logged
%       into system.
%
%   LOAD_VAR('change', 'field', VALUE)
%   LOAD_VAR('change', 'field', VALUE, 'user', 'username') Change variable in
%       user defined structure. 'username' defines user other than currently logged
%       into system.
%
%   LOAD_VAR('createuser') Create new structure for defined user logged in. 
%   LOAD_VAR('createuser', 'username') Create new structure for defined
%       user. 
%
%   output = LOAD_VAR('getvalue', 'field')
%   output = LOAD_VAR('getvalue', 'field', 'user', 'username') Output of values from a field.
%
%   usage in functions:
%   either
%       function output = foo()
%           output = LOAD_VAR('getvalue', 'username'); % get variable
%           'username' back
%
%   or
%   LOAD_VAR  % load variable structure into workspace first
%       
%       function output = foo()
%           output = evalin('base', 'vars.username'); % get variable
%           'username' back



% select strings which might be potential keywords
numIndex = find(cellfun('isclass', varargin, 'char'));

% structures will be saved in mat files (for each user) in the directory of load_var
fundir = fileparts(which('load_var')); % directory of this function
vars = struct;

% Load variables to workspace
if max(ismember(lower(varargin(numIndex)), 'user'))
    if length(varargin) > find(ismember(lower(varargin(numIndex)), 'user') > 0)
        user = varargin{numIndex(ismember(lower(varargin(numIndex)), 'user') > 0) + 1};
    else
        error('Incorrect use of function. Better: load_var([...,]''user'',username)')
    end
else
    % get user name from system
    user = getusername;
end

if max(ismember(lower(varargin(numIndex)), 'createuser'))
     % do nothing here
elseif exist([user '.mat'], 'file')
    load(fullfile(fundir, [user '.mat']));
else
    disp(['User ''' user ''' does not exist. Use ' mfilename '(''createuser'') instead.']);
    return;
end


if ~isempty(varargin)
    switch lower(varargin{1})
        case 'add'
            field = varargin{2};
            if isempty(regexp(field,'vars\.', 'once')) || regexp(field,'vars\.', 'once') > 1
                field = ['vars.' field];
            end
            
            value = varargin{3}; %#ok<*NASGU>

            % check whether field is already present
            % if you know a better implementation, please improve
            temp1 = regexp(field,'\.\w+$', 'split');  % first half of field until last dot
            temp2 = regexp(field,'\w+(?!.*\w+)','match'); % last fieldname
            try
                existfield = eval(['isfield(' cell2mat(temp1) ',''' cell2mat(temp2) ''')']);
            catch
                existfield = 0;
            end
            if ~existfield
                eval([field '= value;']);  % add field and value to structure
                save(fullfile(fundir, [user '.mat']), 'vars');
                assignin('base', 'vars', vars); % assign structure to workspace
            else
                disp(['Field ''' field ''' already exists! - Didn''t change anything.'])
            end
        case 'change'
            field = varargin{2};
            if isempty(regexp(field,'vars\.', 'once')) || regexp(field,'vars\.', 'once') > 1
                field = ['vars.' field];
            end
            value = varargin{3};
            
            % check whether there are fields downstream which might get
            % overwritten
            try
                existfield = isempty(evalc(['fieldnames(' field ');']));
            catch
                existfield = 0;
            end
            if ~existfield
                eval([field '= value;'])  % change value
                save(fullfile(fundir, [user '.mat']), 'vars');
                assignin('base', 'vars', vars); % assign structure to workspace
            else
                disp(['Field ''' field ''' has following subfields which would be deleted! - Didn''t change anything.'])
                eval(['fieldnames(' field ')'])
            end
        case 'getvalue'  
            field = varargin{2};
            if isempty(regexp(field,'vars\.', 'once')) || regexp(field,'vars\.', 'once') > 1
                field = ['vars.' field];
            end
            try
                eval(['output = ' field ';']);
            catch
                output = [];
                disp(['Field ''' field ''' does not exist for user ''' user '''.'])
            end
        case 'createuser'
            if length(varargin) > 1
                user = varargin{2};
            end
            if ~exist(fullfile(fundir, [user '.mat']), 'file')
                vars.username = user;
                save(fullfile(fundir, [user '.mat']), 'vars');
                disp(['Variable structure for user ''' user ''' is created.']);
                assignin('base', 'vars', vars); % assign structure to workspace
            else
                disp(['Variable structure for user ''' user ''' already exists.']);
            end
        case 'user'
            disp(['Loaded variables for user ''' user ''' into workspace']);
            assignin('base', 'vars', vars); % assign structure to workspace
        otherwise
            error([varargin{1} ' not used as keyword'])
    end %switch
else
    assignin('base', 'vars', vars); % assign structure to workspace
end
